<template>
    <div class="app-container">
        <div v-if="nextStep">
            <el-form
                ref="formDesgin"
                :model="formDesgin"
                :rules="desginRules"
                class="el-form"
                label-position="top"
                label-width="120px">
                <el-row class="addTitle">
                    <h2>方法设计</h2>
                </el-row>
                <div class="formBody">
                     <el-tree 
                        class="tree-border"
                        :data="methodList"
                        show-checkbox
                        ref="menu"
                        node-key="taskId"
                        :check-strictly="false"
                        empty-text="加载中，请稍后"
                        :props="defaultProps"
                    >
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span v-if="data.methodExplain">
                            <span class="row">{{ node.label }}</span>
                        </span>
                        <span v-else>
                            <span class="row" >
                                {{ node.label }}
                            </span>
                            <!-- <span>
                                
                            </span> -->
                            <span>
                                <el-switch v-model="data.selectType" active-text="按成员分配" inactive-text="按机构分配" class="selectType"  inactive-color="#13ce66" @change= selectTypeFun(data)>
                                </el-switch>
                                <template v-if="data.selectType">
                                    <el-select v-model="data.assignIds" multiple class="labelWidth2"   collapse-tags  @change="handleAssign($event,'userOptions')" placeholder="请选择" >
                                        <el-option
                                        v-for="item in userOptions"
                                        :key="item.id"
                                        :label="item.label"
                                        :value="item.id">
                                        </el-option>
                                    </el-select>
                                </template>
                                 <template v-else>
                                     <el-select v-model="data.assignIds" multiple  class="labelWidth2"  collapse-tags  @change="handleAssign($event,'agencyOptions')" placeholder="请选择"  >
                                                <el-option
                                                    v-for="item in agencyOptions"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value">
                                                </el-option>
                                    </el-select>
                                </template>
                                 <el-input
                                    class="remark"
                                    v-model="data.remark"
                                    placeholder="工作要求"
                                />
                            </span>
                        </span>
                    </span>
                    </el-tree>
                    <el-row class="finishRow">
                        <el-button @click="cancelStep">上一步</el-button>
                        <el-button type="primary" @click="finishcomit">完成</el-button>
                    </el-row>
                </div>
            </el-form>
        </div>
        <div v-else>
            <el-form
                ref="formData"
                :model="formData"
                :rules="rules"
                class="el-form"
                label-position="top"
                label-width="120px">
                <el-row class="addTitle">
                    <h2>新建场地/分区</h2>
                </el-row>
                <div class="formBody">
                     <el-row>
                        <el-form-item
                        label="名称"
                        prop="zoneName"
                        class="">
                           <el-input class="labelWidth"
                                v-model="formData.zoneName"
                            />
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item
                        label="所在区域"
                        prop="address"
                        class="">
                            <el-cascader
                                class="addressOptions"
                                size="large"
                                :options="addressOptions"
                                v-model="formData.addressOptions"
                            >
                            </el-cascader>
                            <el-input
                                class="address"
                                v-model="formData.address"
                                placeholder="XX街道XXXXXXX"
                            />
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item
                        label="负责人"
                        prop="userId"
                        class="">
                            <el-select v-model="formData.userId" filterable @change="resetUserInfo($event)" placeholder="请选择" class="labelWidth"   >
                                        <el-option
                                            v-for="item in userOptions"
                                            :key="item.id"
                                            :label="item.label"
                                            :value="item.id">
                                            </el-option>
                            </el-select>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item
                        label="负责人联系方式"
                        prop="telephone"
                        class="">
                           <el-input class="labelWidth"
                           :disabled="true"
                            v-model="formData.telephone" />
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item
                        label="面积/m²"
                        prop="acreage"
                        class="">
                           <el-input class="labelWidth"
                           type="number"
                                v-model="formData.acreage"
                            />
                        </el-form-item>
                    </el-row>
                    <!-- <el-row>
                        <el-form-item
                        label="类型"
                        prop="zoneType"
                        class="">
                           <el-select v-model="formData.zoneType"  class="labelWidth" filterable placeholder="请选择" :disabled="Boolean(this.zoneId)" >
                                    <el-option
                                        v-for="item in proTypeOptions"
                                        :key="item.id"
                                        :label="item.label"
                                        :value="item.id">
                                    </el-option>
                            </el-select>
                        </el-form-item>
                    </el-row> -->
             
                    <el-row>
                    <el-form-item
                    label="法定代表人"
                    prop="corporation"
                    class="">
                    <el-input class="labelWidth"
                            v-model="formData.corporation"
                        />
                    </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item
                        label="业主名称"
                        prop="ownerName"
                        class="">
                        <el-input class="labelWidth"
                                v-model="formData.ownerName"
                            />
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item
                        label="业主社会信用代码"
                        prop="creditCode"
                        class="">
                        <el-input class="labelWidth"
                                v-model="formData.creditCode"
                            />
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item
                        label="所属行业"
                        prop="industryType"
                        class="">
                        <el-input class="labelWidth"
                                v-model="formData.industryType"
                            />
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item
                        label="调查周期"
                        prop="beginDate"
                        class="">
                            <el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="开始日期" v-model="formData.beginDate" class="startTime"></el-date-picker>
                            <el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="结束日期" v-model="formData.endDate" class="endTime"></el-date-picker>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="绘制勘探路线">
                            <div class="myMap">
                                <mymap @saveDraw="saveDraw"/>
                            </div>   
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item
                        label="概况"
                        prop="pzExplain"
                        class="">
                             <el-input
                                class="labelWidth"
                                type="textarea"
                                :rows="4"
                                placeholder="请输入内容"
                                v-model="formData.pzExplain">
                            </el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-button type="primary" @click="submitForm">下一步</el-button>
                        <el-button @click="cancel">取 消</el-button>
                    </el-row>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import { listUserAll} from "@/api/system/user";
import { listAgencyAll } from "@/api/system/agency";
import { addProZone,updateProZone,updateProZoneTask} from "@/api/project/project";
import { listMethod2} from "@/api/method/method";
import mymap from '../components/smallMap.vue';
export default {
    name: 'addZone',
    components:{
        mymap
        },
    data() {
        return {
            formData:{
                projectId:"",
                zoneName:undefined,
                address:undefined,
                userId:undefined,
                zoneType:"0",
            },
            rules:{
                 zoneName: [
                    { required: true, message: "名称不能为空", trigger: "blur" }
                ],
                address: [
                    { required: true, message: "所在区域不能为空", trigger: "blur" }
                ],
                userId: [
                    { required: true, message: "项目负责人不能为空", trigger: "blur" }
                ],
                zoneType:[
                     { required: true, message: "场地类型必须选择", trigger: "blur" }
                ]
            },
           //地址选择
            addressOptions: this.regionData,
            //用户选择Options
            userOptions:[],
            //机构选择
            agencyOptions:[],
            //项目类型
            proTypeOptions:[{"id": "0","label": "路探"},
             {"id": "1","label": "场地污染"}],
            //下一步页面
            nextStep:false,
            //创建后得zoneId
            zoneId:undefined,
            //设计方法
            formDesgin:{},
            desginRules:{},
            methodList:[],
            loading:false,
            defaultProps:{
                children: "methodTasks",
                label: "taskName"
            },
            
        };
    },
    mounted() {
        this.formData.projectId= this.$route.params.ID;
        this.getOptionsUser();
        this.getList()
        // console.log(this.$route)
    },
    methods: {
          //获取机构用户列表，并转为options数据
        getOptionsUser(){
            const Params = {
                pageNum: 1,
                pageSize: 10000};
            listUserAll().then(
                response => {
                    this.userOptions = response.data.map(item => { return {"id":item["userId"],"label":item["userName"],"telephone":item["telephone"],"agencyId":item["agencyId"]} })  
                }
            );
            listAgencyAll().then(
                response => {
                    this.agencyOptions = this.resetOptions(response.data,"agencyId","agencyName");
                }
            )
        },
        //用户选择联动
        resetUserInfo(value){
            const valueObj= this.userOptions.find((item)=>{return item.id === value;});
            this.formData.userName = valueObj.label;
            this.formData.telephone = valueObj.telephone;
            this.formData.agencyId = valueObj.agencyId
        },
        //下一步提交
        submitForm(){
            this.$refs["formData"].validate((valid) => {
                if (valid) { 
                    if(this.zoneId){
                        this.formData.zoneId = this.zoneId
                        updateProZone(this.formData).then(
                            response=>{
                                this.nextStep = true
                                this.zoneId = response.msg
                            }
                        )
                    }
                    else{
                        addProZone(this.formData).then(response => {
                                this.nextStep = true
                                this.zoneId = response.msg
                            });
                    }
                }})  
            
        },
        //取消新建场地
        cancel(){
            let view = this.$route
            this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
                if (this.isActive(view)) {
                    this.toLastView(visitedViews, view)
                }
            })
            // this.$router.push({ name:'Project',params:{projectId:this.projectId}})
        },
        isActive(route) {
            return route.path === this.$route.path
        },
        toLastView(visitedViews, view) {
            const latestView = visitedViews.slice(-1)[0]
            if (latestView) {
                if (latestView.name === "User") {
                    this.changeActiveMenu();
                }
                this.$router.push(latestView.fullPath)
            } else {
                // now the default is to redirect to the home page if there is no tags-view,
                // you can adjust it according to your needs.
                if (view.name === 'User') {
                    // to reload home page
                    this.$router.replace({ path: '/redirect' + view.fullPath })
                } else {
                    this.changeActiveMenu();
                    this.$router.push({ name:'Project',params:{projectId:this.projectId}})
                    
                }
            }
        },
        changeActiveMenu() {
            const routes = this.$store.getters.permission_routes;
            routes.forEach(route => {
                if (route.name === "System") {
                    this.$store.dispatch("SetActiveMenu", route);
                }
            });
        },
        //上一步
        cancelStep(){
            this.nextStep = false
        },
        /** 查询方法列表 */
        getList() {
            // 查询条件
            this.loading = true
            listMethod2().then(
                response => {
                    if(response.data){
                        this.methodList = response.data;
                        this.methodList.map(item=>{
                            item.taskId = item.methodId
                            item.taskName = item.methodName
                            if(item.methodTasks){
                                item.methodTasks.map(a=>{
                                    a.selectType = true
                                })
                            }
                        })
                        this.loading = false;
                    }
                    
                }
            );
        },
        // 所有权限菜单节点数据
        getMenuAllCheckedKeys() {
            // 目前被选中的菜单节点
            let checkedKeys = this.$refs.menu.getCheckedKeys();
            let redata = []
            checkedKeys.forEach(item1 =>{
                this.methodList.forEach(item2=>{
                    if(item2.taskId ==item1){
                        let tag = {
                            methodId:item2.taskId,
                            tasks:[]
                        }
                        item2.methodTasks.forEach(item3=>{
                            let assignType=""
                            if(item3.selectType){
                                assignType = "0"
                            }else{
                                assignType = "1"
                            }
                            let task={
                                "taskId":item3.taskId,
                                "assignType":assignType,
                                "ids":item3.assignIds,
                                "remark":item3.remark
                            }
                            tag.tasks.push(task)
                        })
                    redata.push(tag)
                    }
                })
            })
         
            return redata;
        },
        //修改完成
        finishcomit(){
            let data = {
                    "zoneId":this.zoneId,
                    "assign":this.getMenuAllCheckedKeys()
            }
            updateProZoneTask(data).then(response => {
                this.msgSuccess("添加成功");
                let view = this.$route
                this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
                    if (this.isActive(view)) {
                        this.toLastView(visitedViews, view)
                    }
                })
                this.nextStep = false
            })
        },
         //指派对象操作
        handleAssign(val,ty){
            let valueObj="";
            if(ty=='userOptions'){
                valueObj= this.userOptions.filter(
                    (item)=>{return item.id == val;});
            }
            else{
                valueObj= this.agencyOptions.filter((item)=>{return item.value == val;});
            }
            // this.taskForm.assignName = valueObj.label;
        },
        //选择机构和成员切换
        selectTypeFun(data){
            this.methodList.map(item=>{
                if(item.methodTasks){
                    item.methodTasks.map(a=>{
                        if(a.taskId == data.taskId)
                                    a.assignIds = []
                        })
                }
            })
            // data.assignIds = []
        }, 
        //绘制区域
        saveDraw(val){
            this.formData.polygonList = val[0]
            // console.log(val)
        }
    },
};
</script>

<style lang="scss" scoped>
.el-form{
    background: #fff;
    .addTitle{
        padding-left: 20px;
    }
    .formBody{
        padding: 0px 40px 40px 40px;
        .address{
            width:320px;
            margin-left: 20px;
        }
        .addressOptions{
            width: 300px;
        }
        .labelWidth{
            width: 640px;
        }
        .labelWidth2{
            width: 350px;
        }
        .startTime,.endTime{
            width: 310px;
            margin-right: 20px;
        }
        .row{
            display: inline-block;
            // height: 50px;
            width: 250px;
        }
        .selectType{
            margin-right: 5px;
        }
        .remark{margin-left: 20px;width: 700px;}
    }
}
.finishRow{
    margin-top: 20px;
}
.myMap{
    position: relative;
    width: 50%;
    height: 500px;
    border: 1px solid #BFBFBF;
}
</style>